package cn.gwm.flink.streaming.function.map;

import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.common.functions.RichMapFunction;

import java.util.Set;

/**
 * @author : GW00280745
 * @date : 2023/1/15 11:32
 * @description :
 */
public class ChargePredictSrcStandardMapFunction extends RichMapFunction {
    private JSONObject fieldJson;
    public ChargePredictSrcStandardMapFunction(JSONObject fieldJson){
        this.fieldJson = fieldJson;
    }
    private String body="body";
    private String type="type";
    private String id="id";
    private String char3="#";
    private String blankStr="";
    @Override
    public Object map(Object value) throws Exception {
        JSONObject line = JSONObject.parseObject(value.toString());
        if (line.containsKey(body) && line.containsKey(type) && line.containsKey(id)){
            line = line.getJSONObject(body);
        }
        JSONObject jsonObject = new JSONObject();
        Set<String> keySet = fieldJson.keySet();
        for (String key : keySet) {
            //key是标准化字段 value是源数据字段
            String fieldVal = fieldJson.getString(key);
            String[] split = fieldVal.split(char3);
            if (split==null ){
                //如果没有value字段那么value的默认值就是key
                split = new String[]{key};
            }
            //有value字段，value是否配置了默认值
            String defaultStr = split.length == 2 ? split[1] : blankStr;
            String srcFieldName = split[0];
            jsonObject.put(key,line.getOrDefault(srcFieldName,defaultStr));
        }
        return jsonObject;
    }
}
